package imoney.server;

import imoney.server.util.DataStoreManager;
import imoney.server.util.IDsManager;
import imoney.server.util.PersistenceManagerFacto;
import imoney.shared.*;
import imoney.shared.exception.AlreadyExistingException;
import imoney.shared.model.Group;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// TODO : update javadoc.
/**
 * Pour l'instant une servlet de test pour la gestion des groupes.
 * 
 * 	THIS SERVLET WAS UN-MAPPED (31/05/2011).
 * 
 * It is being kept here for reference.
 * 
 * @author Arnaud PELOQUIN
 *
 */
public class GroupServlet extends HttpServlet {
	ArrayList<String> persons = new ArrayList<String>();
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		resp.getWriter().write("Cette page aurait du être accédée via un doPost, désolé pour le dérangement");
		RequestDispatcher dispatch = req.getRequestDispatcher(Statics.DEFAULT_ERROR_URL);
		dispatch.forward(req, resp);
		
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		//TODO : crée un module pour remplacer la servlet : plus ergonomique qu'un chargement de page...
		String temp="";
		@SuppressWarnings("unchecked")
		Enumeration<String> enumNames = req.getParameterNames();
		
		// recuperation des groupes
		while(enumNames.hasMoreElements()){
			temp=enumNames.nextElement();
			if(temp.startsWith("pers")){
				// TODO : modify this test with persons being String if this test is needed again.
				//persons.add(Integer.parseInt(req.getParameter(temp).substring(0, 1)));
			}
		}
		
		resp.getWriter().write("<head><meta http-equiv='Content-Type' content='text/html; charset='ISO'>" +
				"<title>Account</title></head>" +
				"<p>Page de traitement temporaire des donnees groupes<br/>" +
				"Ou des tests sur l'acces au datastore pourront etre effectues sur la persistences, les keys, etc...<br/>");
		// DATA TESTING -------------------------------------
		testData(req,resp);
	}
	
	
	private void testData(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		PersistenceManagerFactory pmf = PersistenceManagerFacto.getPMF();
		PersistenceManager pm = pmf.getPersistenceManager();
		
		// GROUP REGISTERING
		String name = req.getParameter("name");
		String banker = req.getParameter("banker");
		Group group = new Group(persons,name,banker);
		try {
			DataStoreManager.registerAndMakePersistent(group);
			DataStoreManager.closePM();
		} catch (AlreadyExistingException e) {
			System.out.println(e.getLocalizedMessage());
		}
		
		// DATA DISPLAY
		@SuppressWarnings("unchecked") // unchecked cast
		List<Group> retrievedGroups = (List<Group>) pm.newQuery("select from "+Group.class.getName()).execute();
		String lesgroupes="";

		for(Group grp : retrievedGroups ){
			lesgroupes += grp.toString()+",      "+grp.getKey()+"<br/>";
			//+", Parent : "+pers.getParentKey()
		}
		resp.getWriter().write("<br/><br/<p>Groups retrouvees dans bdd :<br/>"+lesgroupes+"<p>");
		StringBuffer buff = req.getRequestURL();
		String refresh = "";
		for(int i=0; i<buff.length(); i++){
			refresh += buff.charAt(i);
		}
		resp.getWriter().write("<br/><a href = '"+refresh+"'>Refresh Page</a>");

		
		@SuppressWarnings("unchecked")
		List<IDsManager> idmanager = (List<IDsManager>) pm.newQuery("select from "+IDsManager.class.getName()).execute();
		for(IDsManager manager : idmanager){
			resp.getWriter().write("<br/><br/<p>IDsManager retrouves dans bdd :<br/>"+manager.toString()+"<p>");
		}
		
		// DATA DELETE
		//pm.deletePersistentAll(retrievedPersons);
		
		// KEY TESTING
		/*Key key = KeyFactory.createKey("Person",10);
		Person pers = (Person) pm.getObjectById(Person.class,key);
		resp.getWriter().write("<br/><br/<p>Personne retrouvees by ID :<br/>"+pers.toString()+"<p>");*/

		pm.close();
	}
}
